<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="管线名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pipLineName">
              <a-input v-model="model.pipLineName" placeholder="请输入管线名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="所属区域" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="areaId">
              <j-select-depart placeholder="请选择区域id" v-model="model.areaId" @change="handleGetAreaPip" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="起始管点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pipPointSt">
              <a-input v-model="model.pipPointSt" placeholder="请输入起始管点"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="终点管点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pipPointEd">
              <a-input v-model="model.pipPointEd" placeholder="请输入终点管点"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" flex="center" v-if="showSwitch">
            <a-select
              :showArrow="false"
              :showSearch="true"
              label-in-value
              :value="value"
              placeholder="请输入管点编号"
              style="width: 38%; margin-right: 10px; margin-bottom: 10px"
              :filter-option="false"
              :not-found-content="fetching ? undefined : null"
              @search="fetchUser"
              @change="handleChange"
              @focus="fetchUser"
            >
              <a-spin v-if="fetching" slot="notFoundContent" size="small" />
              <a-select-option v-for="d in data" :key="d.id">
                {{ d.pipNo }}
              </a-select-option>
            </a-select>
            <!--              <Demo @delete="onDeleteItem" :data="data"></Demo>-->
            <div class="transfer-box">
              <div class="left-box">
                <!--      <h4>Available Options</h4>-->
                <ul>
                  <li v-for="item in availableItems" :key="item.pipPointId">
                    <label>
                      <input type="checkbox" v-model="item.selected" />
                      {{ item.pipNo }}
                    </label>
                  </li>
                </ul>
              </div>
              <div class="middle-box">
                <button @click="moveRight" class="move-button">>>></button>
                <button @click="moveLeft" class="move-button"><<<</button>
              </div>
              <div class="right-box">
                <a-timeline>
                  <a-timeline-item
                    v-for="(item, index) in list"
                    :key="item.pipPointId"
                    @dragstart="dragstart(index)"
                    @dragenter="dragenter($event, index)"
                    @dragover="dragover($event, index)"
                    draggable="true"
                  >
                    <label>
                      <input type="checkbox" v-model="item.selected" />
                      {{ item.pipPointNo }}
                    </label>
                  </a-timeline-item>
                </a-timeline>
              </div>
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import Demo from '@/views/paishui/index'

export default {
  name: 'PipLineForm',
  components: {
    Demo,
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        pipLineName: [{ required: true, message: '请输入管线名称!' }],
        areaId: [{ required: true, message: '请输入区域id!' }],
        pipPointSt: [{ required: true, message: '请输入起始管点!' }],
        pipPointEd: [{ required: true, message: '请输入终止管点!' }],
      },
      url: {
        add: '/paishui/pipLine/add',
        edit: '/paishui/pipLine/edit',
        queryById: '/paishui/pipLine/queryById',
      },
      lineList: [],
      //搜索框字段
      data: [],
      value: '',
      text: '',
      fetching: false,
      availableItems: [
        { pipPointId: 1, pipNo: '2YS1776', selected: false },
        { pipPointId: 2, pipNo: '2YS1775', selected: false },
        { pipPointId: 3, pipNo: '2YS1774', selected: false },
        { pipPointId: 4, pipNo: '2YS1773', selected: false },
        { pipPointId: 5, pipNo: '2YS1772', selected: false },
      ],
      list: [],
      // 源对象的下标
      dragIndex: '',
      // 目标对象的下标
      enterIndex: '',
      timeout: null,
      showSwitch: false,
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  destroyed() {
    // 每次离开当前界面时，清除定时器
    clearInterval(this.timeout)
    this.timeout = null
    this.showSwitch = false
  },
  methods: {
    handleGetAreaPip(storeVals) {
      const arr1 = storeVals.split(',')
      getAction(`/paishui/pipPoint/areaPip/${arr1}`).then((res) => {
        let temporary = res.result
        this.getdata(temporary)
      })
    },
    getdata(val) {
      console.log('valvalval', val)
      this.availableItems = val
      this.showSwitch = true
      if (val == '') {
        this.showSwitch = false
      }
    },
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.model = Object.assign({}, record)
      let jsonArr = JSON.parse(record.pipPointInfo)
      let arr = []
      for (let i = 0; i < jsonArr.length; i++) {
        this.list.push({ pipPointId: jsonArr[i].pipPointId, pipPointNo: jsonArr[i].pipPointNo, selected: false })
      }
      this.visible = true
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'post'
          }
          const newArr = this.list.map((item, index) => {
            console.log(item)
            // if (item.id == undefined) item.id = item.pipPointId
            // return { ...item, position: index + 1 };
            return {
              pipPointId: item.pipPointId,
              pipPointNo: item.pipPointNo,
              sort: index + 1,
            }
          })
          console.log('newArr', newArr)
          console.log('this.model', this.model)
          this.model.pipPointList = newArr
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    /*
     * 文本框值变化时回调
     * */
    fetchUser(value) {
      console.log('fetching user', value)
      this.lastFetchId += 1
      const fetchId = this.lastFetchId
      this.data = []
      this.fetching = true
      if (value == undefined) value = ''
      getAction(`/paishui/pipPoint/list?pipNo=*${value}*`).then((res) => {
        this.data = res.result.records
        console.log('this.data======', this.data)
      })
    },
    /*
     * 选中 option，或 input 的 value 变化时
     * */
    handleChange(value, option) {
      console.log('value value', value)
      console.log('option option', option)
      // console.log('value label',value.label.split('\n'))
      const str = value.label
      const trimmedStr = str.trim()
      console.log('trimmedStr=====', trimmedStr.split(' ')[0])
      this.list.push({ pipPointId: value.key, pipPointNo: trimmedStr.split(' ')[0], selected: false })
      Object.assign(this, {
        value,
        data: [],
        fetching: false,
      })
    },
    moveRight() {
      let add = this.availableItems.filter((v) => v.selected)
      for (let i = 0; i < add.length; i++) {
        this.list.push({ pipPointId: add[i].pipPointId, pipPointNo: add[i].pipNo, selected: false })
      }
      for (let i = 0; i < this.availableItems.length; i++) {
        this.availableItems[i].selected = false
      }
    },
    moveLeft() {
      this.list = this.list.filter((v) => !v.selected)
    },
    dragstart(index) {
      console.log('start index ===>>> ', index)
      this.dragIndex = index
    },

    // dragenter 和 dragover 事件的默认行为是拒绝接受任何被拖放的元素。
    // 因此，我们要在这两个拖放事件中使用`preventDefault`来阻止浏览器的默认行为
    dragenter(e, index) {
      e.preventDefault()
      this.enterIndex = index
      if (this.timeout !== null) {
        clearTimeout(this.timeout)
      }
      // 拖拽事件的防抖
      this.timeout = setTimeout(() => {
        if (this.dragIndex !== index) {
          const source = this.list[this.dragIndex]
          this.list.splice(this.dragIndex, 1)
          this.list.splice(index, 0, source)
          // 排序变化后目标对象的索引变成源对象的索引
          this.dragIndex = index
        }
      }, 100)
    },
    dragover(e, index) {
      e.preventDefault()
    },
  },
}
</script>

<style lang="less" scoped>
.transfer-box {
  display: flex;
  justify-content: center;
  align-items: center;
}

.left-box {
  width: 45%;
  padding-right: 20px;
  border-right: 1px solid #e1e3e6;
}

.right-box {
  width: 45%;
  padding: 0 20px;
  border-left: 1px solid #e1e3e6;
}

.middle-box {
  width: 10%;
  text-align: center;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  margin-bottom: 10px;
}

button {
  display: block;
  margin: 10px auto;
}
.ant-timeline-item {
  padding: 0 0 10px;
}
.move-button {
  border: 1px solid #1890ff;
  border-radius: 5px;
  background: white;
  color: #1890ff;
}
</style>
